package com.rong.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

import com.king.util.file.json.JsonUtil;
import com.rong.common.context.Context;
import com.rong.common.util.HttpRequestUtil;

//@WebServlet( urlPatterns ={ "/service" } , asyncSupported = true )
public class Service extends BaseServlet
{

	private static final long serialVersionUID = 1L;

	public void doGet( HttpServletRequest request , HttpServletResponse response )
			throws ServletException , IOException
	{
		doPost(request, response);
	}

	@SuppressWarnings( "unchecked" )
	public void doPost( HttpServletRequest request , HttpServletResponse response ) throws ServletException ,
			IOException
	{
		
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-type","text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		Context.addParam("@session", request.getSession());
		String p = request.getParameter("p");
		
		if( "login".equals(p) ) //登陆
		{
			login( request , out );
			return;
		}	
		if( "logout".equals(p) ) //登出
		{
			logout( request , response );
			return;
		}	

		/** 初始化数据 */
		try
		{
			initParamToContext(request, response);
		}
		catch ( Exception e )
		{
			out.print(getExceptionResult("参数初始化异常!"+e.getMessage()));
			e.printStackTrace();
		}
		
		/** 从上下文中获取请求接口的参数 */
		Map<String, Object> params = Context.getContextMap();
		
		/** 从配置文件中读取服务端接口地址  */
		String url = PropertiesUtil.getInstance("serive.properties").getStringValue("serviceUrl");
		
		/** HTTP方式请求服务端接口  */
		Logger.getLogger("").info("***************************************			请求接口开始		***************************************");
		try
		{
			
			Logger.getLogger("").info("						请求接口:"+url + "/?p="+params.get("p"));
			Logger.getLogger("").info("						请求参数:"+ params );
			
			/** 判断用户是否已登陆 */
			boolean isLogin = false;
			
			if( null!=request.getSession().getAttribute("loginUser"))
			{
				Context.addParam("loginUser", request.getSession().getAttribute("loginUser").toString());
				isLogin = true;
				params.put("mobile", true);
				params.put("loginUserName", request.getSession().getAttribute("loginUserName"));
			}
			
			Logger.getLogger("").info("						是否已登陆:"+ isLogin );
			
			String result = HttpRequestUtil.doGetP2P( params , url ,isLogin );
			
			if( null!=result && !"".equals(result.trim()))
			{
				result = result.replace("&lt;", "<");
				result = result.replace("&gt;", ">");
				result = result.replace("&nbsp;"," ");
				result = result.replace("&quot;","\\\"");
			}	
			
			Logger.getLogger("").info("						返回结果:\n"+result);
			out.print(result);
		}
		catch ( Exception e )
		{
			out.print(getExceptionResult("请求异常," +e.getMessage()));
			e.printStackTrace();
			Logger.getLogger("").info("						请求异常:"+e.getMessage());
			
		}
		finally
		{
			Logger.getLogger("").info("***************************************			请求接口结束		***************************************");
		}
		
		out.flush();
		out.close();
		Context.release();
	}

	/**
	* <pre>
	* 功能说明：退出登录
	* 创建日期：2015-9-25
	* 修改记录：
	* </pre>
	* @author king
	* @version v1.0
	* @param request
	* @param response
	 * @throws IOException 
	*/
	private void logout( HttpServletRequest request , HttpServletResponse response ) throws IOException
	{
			request.getSession().removeAttribute("loginUser");
			response.sendRedirect("page?p=login");
	}

	/**
	* <pre>
	* 功能说明：系统登陆
	* 创建日期：2015-9-25
	* 修改记录：
	* </pre>
	* @author king
	* @version v1.0
	* @param request
	* @param response
	 * @throws IOException 
	*/
	@SuppressWarnings( "rawtypes" )
	private void login( HttpServletRequest request , PrintWriter out ) throws IOException
	{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		try
		{
			/** 从配置文件中读取服务端接口地址  */
			String url = PropertiesUtil.getInstance("serive.properties").getStringValue("serviceUrl");
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("username", username );
			params.put("password", password );
			params.put("p", "sys" );
			params.put("m", "login" );
			params.put("mobile", "true" );
			String result = HttpRequestUtil.doGetP2P( params , url , true );
			Map map = (Map) JsonUtil.getInstance("UTF-8").parseJsonToObject(result, Map.class);
			
			System.out.println(  "--------------------------loginUser------------------------"+ map.get("loginUser"));
			request.getSession().setAttribute("loginUser", map.get("loginUser"));
			request.getSession().setAttribute("loginUserName", username);
			
			out.print(result);
		}
		catch ( Exception e )
		{
			e.printStackTrace();
			out.print(getExceptionResult("请求异常," +e.getMessage()));
		}
	}

}
